<template>
  <Card>
    <Tabs type="card" v-model="tabState" @on-click='changeTab'>
      <TabPane label="待处理" name='[1,2]'> </TabPane>
      <TabPane label="已处理" name='[3]' > </TabPane>
      <TabPane label="已取消" name='[4]' > </TabPane>
    </Tabs>
    <vxe-grid
          highlight-hover-row
          show-header-overflow
          show-overflow
          ref="xGrid"
          height="600"
          align="center"
          :columns="tableColumn"
          :data="tableData"
          :toolbar-config="tableToolbar"
          :edit-config="{
            trigger: 'manual',
            mode: 'row',
            showStatus: true,
            icon: 'fa fa-file-text-o',
          }"
        >
          <template #toolbar_buttons>
            <!-- <Button
              type="primary"
              style="margin-right: 10px"
              @click="agreeList()"
              >批量同意
            </Button> -->
            <Button
              type="primary"
              style="margin-right: 10px"
              icon="md-refresh"
              @click="update()"
              >刷新
            </Button>

          </template>
          <template #toolbar_tools>
            <!-- <vxe-form :data="formData">
            <vxe-form-item title="查找企业名称" field="name" :item-render="{}">
              <template #default="{data}">
                <vxe-input v-model="data.name" placeholder="请输入名称" @change="update()"></vxe-input>
              </template>
            </vxe-form-item>
            </vxe-form> -->
          </template>

          <template #operate="{ row }">
            <Button
              type="primary"
              style="margin-right: 10px"
              @click="viewDetial(row)"
              >详情
            </Button>
            <Button
            type="success"
            style="margin-right: 10px"
            @click="feedback(row)"
            >处理
          </Button>
          <Button
            type="primary"
            style="margin-right: 10px"
            @click="viewHistory(row)"
            v-if="showHistory"
            >记录
          </Button>
          </template>
          <template #pager>
            <div style="text-align: center; padding: 10px">
              <Page
                :current="page.current"
                :total="page.total"
                :page-size="page.pageSize"
                show-elevator
                show-total
                show-sizer
                @on-change="update"
              />
            </div>
          </template>
        </vxe-grid>

        <vxe-modal
          v-model="isModalShow"
          :title="modalTitle"
          width="800"
          min-width="600"
          min-height="300"
          :loading="submitLoading"
          resize
          destroy-on-close
        >
          <template #default>
            <vxe-form
              ref="addFF"
              :data="detailForm"
              title-align="right"
              title-width="100"
              @submit="submitForm()"
            >
                <vxe-form-item title="维修详情" field="repairSpecific" :item-render="{}" span="24" v-if="showDetail">
                <template #default="{ data }">
                    <vxe-textarea v-model="data.workOrderSpecific.repairSpecific" placeholder="只读的" readonly></vxe-textarea>
                </template>
                </vxe-form-item>

                <vxe-form-item title="反馈信息" field="feedbackInfo" :item-render="{}" span="24" v-if="showFeedback">
                <template #default="{ data }">
                    <vxe-textarea v-model="data.feedbackInfo" placeholder="输入处理反馈信息" ></vxe-textarea>
                </template>
                </vxe-form-item>

                <vxe-form-item align="center" span="24" :item-render="{}">
                <template #default>
                    <vxe-button type="submit" status="primary">确定</vxe-button>
                </template>
                </vxe-form-item>

            </vxe-form>
          </template>
        </vxe-modal>

  <vxe-modal
          v-model="showTimeLine"
          title="操作时间轴"
          width="400"
          min-width="600"
          min-height="500"
          :loading="submitLoading"
          resize
          destroy-on-close
        >

        <myTimeLine :timeLines='timeLines'>
        </myTimeLine>

  </vxe-modal>

  </Card>
</template>
<style scoped>
    .time{
        font-size: 14px;
        font-weight: bold;
    }
    .content{
        padding-left: 5px;
    }
</style>
<script>
import axios from '@/libs/api.request'

import myTimeLine from '@/view/components/my-timeLine/my-timeLine.vue'

export default {
  components: { myTimeLine },

  data () {
    return {
      timeLines: [
        {
          time: '1976年',
          content: 'Apple I 问世',
          feedback: null
        },
        {
          time: '1984年',
          content: '发布 Macintosh'
        },
        {
          time: '2007年',
          content: '发布 iPhone'
        },
        {
          time: '2010年',
          content: '发布 iPad'
        },
        {
          time: '2011年10月5日',
          content: '史蒂夫·乔布斯去世'
        }

      ],
      tabState: '[1,2]',
      showFeedback: false,
      showTimeLine: false,
      //   status: null,
      showDetail: false,
      modalTitle: '查看企业信息详情',
      submitLoading: false,
      selectRow: null,
      detailForm: {
        id: 'asdas',
        state: 1,
        applicantName: 'aaa',
        applicantPhone: '15274959567',
        applicantId: 'asdad',
        workOrderSpecific: {
          repairAddress: {
            area: {
              id: 'qweqweq',
              name: 'A区域'
            },
            building: {
              id: '12131ad',
              name: 'A幢'
            },
            unit: {
              id: '1213sd',
              name: 'A单元'
            },
            house: {
              id: '12sada1ad',
              name: 'A房屋'
            }
          },
          repairType: '维修类',
          repairSpecific: '维修电脑'
        },
        typeCode: 1,
        parkId: 'asdasd'
      },
      formData: {
        id: 'asdas',
        state: 1,
        applicantName: 'aaa',
        applicantPhone: '15274959567',
        applicantId: 'asdad',
        workOrderSpecific: {
          repairAddress: {
            area: {
              id: 'qweqweq',
              name: 'A区域'
            },
            building: {
              id: '12131ad',
              name: 'A幢'
            },
            unit: {
              id: '1213sd',
              name: 'A单元'
            },
            house: {
              id: '12sada1ad',
              name: 'A房屋'
            }
          },
          repairType: '维修类',
          repairSpecific: '维修电脑'
        },
        typeCode: 1,
        parkId: 'asdasd'
      },
      tableToolbar: {
        zoom: true,
        custom: true,
        slots: {
          buttons: 'toolbar_buttons',
          tools: 'toolbar_tools'
        }
      },
      tableColumn: [
        { type: 'checkbox', width: 40, fixed: 'left' },
        { field: 'applicantName', title: '申请人姓名', width: 120 },
        { field: 'applicantPhone', title: '申请人电话', width: 120 },
        { field: 'workOrderSpecific.repairType', title: '维修类别' },
        // { field: 'workOrderSpecific.repairSpecific', title: '维修详情' },
        { field: 'addressName', title: '地址信息' },
        {
          field: 'state',
          title: '状态',
          editRender: {
            name: '$select',
            options: [
              { label: '待处理', value: '1' },
              { label: '处理中', value: '2' },
              { label: '已处理', value: '3' },
              { label: '已取消', value: '4' }
            ]
          },
          width: 100
        },
        { title: '操作', width: 270, slots: { default: 'operate' }, fixed: 'right' }
      ],
      page: {
        current: 1,
        total: 20,
        pageSize: 10
      },
      // 展示数据 & 从后端获取来的：
      tableData: [
        {
          id: 'asdas',
          state: '',
          applicantName: 'aaa',
          applicantPhone: '15274959567',
          applicantId: 'asdad',
          workOrderSpecific: {
            repairAddress: {

            },
            repairType: '维修类',
            repairSpecific: '维修电脑'
          },
          typeCode: 1,
          parkId: 'asdasd'
        }
      ]

    }
  },
  mounted () {
    this.update()
  },
  computed: {
    isModalShow: {
      get: function () { // 不能够使用 箭头函数
        return this.showFeedback || this.showDetail
      },
      set: function (value) {
        // this.isModalShow = value
        if (this.showFeedback) {
          this.showFeedback = value
        }
        if (this.showDetail) {
          this.showDetail = value
        }
      }
    },
    showHistory: function () {
    //   console.log(this.tabState === '[3]')

      return this.tabState === '[3]'
    }

  },

  methods: { //
    changeTab (name) {
      this.update()
    },
    update () {
      this.workOrderRepairQuery().then((res) => {
        // console.log(res)
        this.tableData = res.data.msg.records
        console.log(this.tableData)
        this.tableData.map(item => {
          const repairAddress = JSON.parse(item.workOrderSpecific.repairAddress)
          item.addressName = repairAddress.map(item => item.name).reduce((acc, cur) => acc + cur, '')
        })
      }).catch((err) => {
        console.log(err)
      })
    },
    toLine (name) {
      return name.replace(/([A-Z])/g, '_$1').toLowerCase()
    },
    submitForm () {
      this.submitLoading = true
      if (this.showDetail) {
        this.oprateWorkOrder(2, this.detailForm.id).then((res) => {
          this.submitLoading = false
          this.showDetail = false
          this.$Message.success('确认成功')
          this.update()
        }).catch((err) => {
          console.log(err)
        })
      }
      if (this.showFeedback) { // 提交反馈
        this.oprateWorkOrder(3, this.detailForm.id, this.detailForm.feedbackInfo).then((res) => {
          this.submitLoading = false
          this.showFeedback = false
          this.$Message.success('反馈成功')
          this.update()
        }).catch((err) => {
          console.log(err)
        })
      }
    },
    oprateWorkOrder (operationType, workOrderId, feedback = null) {
      return new Promise((resolve, reject) => {
        axios
          .request({
            method: 'post',
            url: 'work_order/operation_record/create',
            data: {
              workOrderId: workOrderId,
              operationType: operationType,
              feedback: feedback
            }
          })
          .then((res) => {
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    workOrderRepairQuery () {
      return new Promise((resolve, reject) => {
        axios
          .request({
            method: 'post',
            url: 'work_order/repair/query',
            data: {
              pageSize: this.page.pageSize,
              pageNum: this.page.current,
              state: JSON.parse(this.tabState)
            }
          })
          .then((res) => {
            console.log('query', res)
            resolve(res)
          })
          .catch((err) => {
            console.log(err)
            reject(err)
          })
      })
    },
    getEnterpriseByName (enterpriseName) {
      return new Promise((resolve, reject) => {
        axios
          .request({
            method: 'get',
            url: 'enterprise/list/all',
            params: {
              enterpriseName: enterpriseName
            }
          })
          .then((res) => {
            resolve(res)
          })
          .catch((err) => {
            console.log(err)
            reject(err)
          })
      })
    },
    agree (row) {
      const ids = new Array(row.id)
      const process = new Promise((resolve, reject) => {
        axios
          .request({
            method: 'post',
            url: 'enterprise/audit/pass',
            params: {
              ids: ids
            }
          })
          .then((res) => {
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
      process.then(() => {
        this.update()
      }).catch((res) => {
        console.log(res)
      })
    },
    agreeList () {
      const selectedRecords = this.$refs.xGrid.getCheckboxRecords()
      console.log(selectedRecords) // row 数组
    },
    search () {
      this.spaceQuery()
    },

    deleteList (row) {
      // 获取选中的数据
      const selectedRecords = this.$refs.xGrid.getCheckboxRecords()
      console.log(selectedRecords)
    },
    viewDetial (row) {
      this.showDetail = true
      this.detailForm = row
    },
    feedback (row) {
      this.showFeedback = true
      this.detailForm = row
    },
    viewHistory (row) {
      this.showTimeLine = true
      //   console.log(row)
      // 查看历史记录 work_order/operation_record/list TODO: 接口有问题，传入id， 返回 空数组
      const process = new Promise((resolve, reject) => {
        axios
          .request({
            method: 'post',
            url: 'work_order/operation_record/list',
            data: {
              workOrderId: row.id
            }
          })
          .then((res) => {
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
      process.then((res) => {
        console.log(res)
        this.timeLines = res.data.msg
      }).catch((err) => {
        console.log(err)
      })
    },
    deleteRow (row) {
      // console.log(row)
      this.$Modal.confirm({
        title: '操作确认',
        content: '您确定要删除"' + row.name + '"吗',
        onOk: () => {
          const spaceId = row.spaceId
          console.log(spaceId)
          axios
            .request({
              method: 'get',
              url: 'space/delete',
              params: {
                spaceId: spaceId
              }
              // data:{ post, 放到请求头里面
              // }
            })
            .then((res) => {
              console.log(res)
              this.update()
              this.$Message.success('删除成功')
            })
            .catch((err) => {
              console.log(err)
            })
          // this.tableData.splice(idx, 1) // 返回被删除的数组
        },
        onCancel: () => {}
      })
    },
    refreshTable () {}
  }
}
</script>
